package cn.szabadsag.user.controller;

import cn.szabadsag.base.exception.BusinessException;
import cn.szabadsag.user.domain.LoginInfo;
import cn.szabadsag.user.domain.dto.UserDto;
import cn.szabadsag.user.service.ILoginInfoService;
import cn.szabadsag.user.service.IUserService;
import cn.szabadsag.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户注册
 *
 * @author yangcong
 * @date 2022年03月12日 10:01
 * @since v1.0
 */
@RestController
public class AccountController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ILoginInfoService loginInfoService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 验证用户注册的数据
     * @param userDto
     * @return
     */
    @PostMapping("/reg")
    public AjaxResult register(@RequestBody UserDto userDto){
        try {
            userService.register(userDto);
            return AjaxResult.me();
        } catch (BusinessException e) {
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }

    /**
     * 验证用户登录的数据
     * @param userDto
     * @return
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody UserDto userDto){
        try {
            System.out.println("登录数据：" + userDto);
            //  根据用户登录的账户查询用户登录数据
            LoginInfo loginInfo = loginInfoService.loadByAccount(userDto);
            System.out.println("用户登录信息数据：" + loginInfo);
            //  生成token
            String token = UUID.randomUUID().toString();
            //  把当前登录用户存储在redis中
            redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);
            //  将token和登录信息返回给前端
            HashMap<String, Object> map = new HashMap<>();
            //  清除敏感数据
            loginInfo.setPassword("");
            loginInfo.setSalt("");
            map.put("token",token);
            map.put("loginInfo",loginInfo);
            //  将token和登录信息返回给前端
            return AjaxResult.me().setResultObj(map);
        } catch (BusinessException e) {
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }


}
